package com.hst.web.base.proxy;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.hst.core.Page;
import com.hst.core.ServiceContext;
import com.hst.core.dao.IORDao;
import com.hst.core.dao.ORQuery;
import com.hst.core.dao.ORQuery.Op;
import com.hst.core.meta.MetaData;
import com.hst.core.meta.proxies.DefaultDataProxy;
import com.hst.core.meta.proxies.OREntityUtils;
import com.hst.web.auth.po.User;
import com.hst.web.base.entity.TCompanyInfo;
import com.hst.web.base.service.UserRoleService;
import com.hst.web.base.ui.CompanyInfo;
import com.hst.web.sys.entity.TRole;

public class CompanyInfoProxy extends DefaultDataProxy{
	
	@Autowired
	IORDao dao;

	@Autowired
	UserRoleService us;
	
	@Autowired
	OREntityUtils orUtil;
	
	@Override
	public Page<?> list(Map<String, ?> query, int pageIdx) {
		List<ORQuery> querys = parseQuery(query);
		User u = (User) ServiceContext.getInstance().getUser();
		TRole role = us.userRole(u.getId());
		if("2".equals(role.getRoleLevel())) {
			querys.add(new ORQuery(Op.eq,"companyCode",u.getCompanyCode()));
		}
		return dao.list(TCompanyInfo.class, querys, pageIdx);
	}
	
	@Override
	public Object save(MetaData data) throws Exception {
		Object data1 = convert2Entity(data);
		if (1 == data.getOp()) {
			CompanyInfo company = (CompanyInfo) data;
			List<ORQuery> querys = new ArrayList<ORQuery>();
			querys.add(new ORQuery(Op.eq,"creditCode",company.getCreditCode()));
			List<TCompanyInfo> companyInfos = dao.list(TCompanyInfo.class,querys);
			if(companyInfos.size() > 0) {
				throw new Exception("社会信用代码重复,不能保存");
			}else {
				dao.save(data1);
			}
		} else {
			CompanyInfo company = (CompanyInfo) data;
			List<ORQuery> querys = new ArrayList<ORQuery>();
			querys.add(new ORQuery(Op.eq,"creditCode",company.getCreditCode()));
			querys.add(new ORQuery(Op.neq,"companyCode",company.getCompanyCode()));
			List<TCompanyInfo> companyInfos = dao.list(TCompanyInfo.class,querys);
			if(companyInfos.size() > 0) {
				throw new Exception("社会信用代码重复,不能保存");
			}else {
				Object data2 = null;
				Serializable pk = (Serializable) orUtil.getEntityPk(data1);
				if (null != pk)
					data2 = dao.get(getEntityClass(), pk);
				if (null == data2)
					dao.save(data1);
				else {
					BeanUtils.copyProperties(data2, data1);
					dao.update(data2);
				}
			}
		}
		return convert2MetaData(data1);
	}
}
